import numpy as np
import matplotlib.pyplot as plt

# 转换成矩阵 resharp
X = np.linspace(0,10,num=30).reshape(-1,1)
# 斜率和截距 随机生成
w = np.random.randint(1,5,size=1)
b = np.random.randint(1,10,size=1)

#根据一元一次方程计算目标值y,并加上噪声，数据有上下波动
y = X * w + b + np.random.randn(30,1)
plt.scatter(X,y)
# plt.show()
# 重新构造X,b截距，相当于系数w0,前面统一乘1
X = np.concatenate([X,np.full(shape=(30,1),fill_value=1)],axis=1)
# 正规方程求解
wb = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y).round(2)
print("一元一次方程真实的斜率和截距是:", w, b)
print("通过正规方程求解的斜率和截距是:", wb)
# 根据求解的斜率和截距绘制线性回归线型图
print(X)
print(wb)
print(X.dot(wb))
plt.plot(X[:,0],X.dot(wb),color='r')
plt.show()


